package com.coai.message.repository

import com.coai.message.model.MessageReadStatus
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.jpa.repository.Modifying
import org.springframework.data.jpa.repository.Query
import org.springframework.stereotype.Repository

@Repository
interface MessageReadStatusRepository : JpaRepository<MessageReadStatus, String> {
    
    fun findByMessageIdAndUserId(messageId: String, userId: String): MessageReadStatus?
    
    fun existsByMessageIdAndUserId(messageId: String, userId: String): Boolean
    
    @Query("""
        SELECT mrs.userId FROM MessageReadStatus mrs
        WHERE mrs.messageId = :messageId
    """)
    fun findUserIdsByMessageId(messageId: String): List<String>
    
    @Modifying
    @Query("""
        INSERT INTO MessageReadStatus (messageId, userId, readAt)
        SELECT m.id, :userId, CURRENT_TIMESTAMP
        FROM Message m
        WHERE m.conversationId = :conversationId
        AND m.senderId != :userId
        AND NOT EXISTS (
            SELECT 1 FROM MessageReadStatus mrs
            WHERE mrs.messageId = m.id AND mrs.userId = :userId
        )
    """)
    fun markAllAsRead(conversationId: String, userId: String)
}
